import os
import sys
from django.conf import settings

DEBUG = os.environ.get('DEBUG','on') == 'on'
settings.configure(DUBUG = DEBUG,
	SECRET_KEY = 'thisisthesecrekey',
	ROOT_URLCONF = __name__,
	ALLOWED_HOSTS = ['*'],
	MIDDLEWARE_CLASSES = ['django.middleware.common.CommonMiddleware',
		'django.middleware.csrf.CsrfViewMiddleware',
		'django.middleware.clickjacking.XFrameOptionsMiddleware',])

from django import forms
from django.conf.urls import url
from io import BytesIO
from PIL import Image,ImageDraw
from django.http import HttpResponse

class ImageForm(forms.Form):
	height = forms.IntegerField(min_value=1,max_value=2000)
	width = forms.IntegerField(min_value=1,max_value=2000)

	def generate(self,image_format='PNG'):
		height = self.cleaned_data['height'];
		width = self.cleaned_data['width'];
		image = Image.new('RGB',(width,height));
		content = BytesIO();
		image.save(content,image_format)
		content.seek(0)
		return content;

	def generate1(self,image_format='PNG'):
		height = self.cleaned_data['height'];
		width = self.cleaned_data['width'];
		image = Image.new('RGB',(width,height));
		###在图片中间 画上一些文字信息
		draw = ImageDraw.Draw(image);
		text = '{} X {}'.format(width,height);
		textwidth,textheight = draw.textsize(text);
		if textwidth < width and textheight < height:
			texttop = (height - textheight) // 2
			textleft = (width - textwidth) // 2
			draw.text((textleft,texttop),text,fill=(255,255,255))
		### 结束
		content = BytesIO();
		image.save(content,image_format)
		content.seek(0)
		return content;

def img(request,width,height):
	form = ImageForm({'height':height,'width':width});
	if form.is_valid():
		#height = form.cleaned_data['height'];
		#width = form.cleaned_data['width'];
		#return HttpResponse('OK');
		img = form.generate1()
		return HttpResponse(img,content_type='image/PNG');
	else:
		return HttpResponseBadRequest('111111111111111');


#HttpResponse('OK');
#	页面打印 OK
#return HttpResponseBadRequest('111111111111111');
#	页面打印 Server Error (500)

urlpatterns = [url(r'^imgage/(?P<width>[0-9]+)x(?P<height>[0-9]+)$',img),]


if __name__ == "__main__":
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)
